<?php

namespace App\Console\Commands\WorkOrder;

use App\Models\Common\ResourcesModel;
use App\Models\Recognize\RecognizeBusinessLicenseResult;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;
use Kuafu\File\PrivateFileUtil;
use Kuafu\Recognizer\RecognizeBusinessLicense;

class TransferBusinessLicenseImage extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'work_order:transfer_business_license_image';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '【工单】转换营业执照文件，并存下识别结果';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        ResourcesModel::query()
            ->where('module', 'WORK_ORDER')
            ->where('business', 'FUNCTION_OPEN')
            ->where('name', 'businessLicenseImg')
            ->orderBy('id', 'asc')
            ->chunk(100, function ($models) {
                foreach ($models as $model) {
                    if (!strlen($model->url)) {
                        echo 'x';
                        continue;
                    }
                    $url     = ltrim(parse_url($model->url, PHP_URL_PATH), '/');
                    $suffix  = FileUtil::guessSuffix($url);
                    $fullUrl = $model->isPublic
                        ? FileUtil::domain() . '/' . $url
                        : PrivateFileUtil::signUrl($url);
                    $tmpFile = sys_get_temp_dir() . '/' . Str::random() . $suffix;
                    try {
                        (new Client())->get($fullUrl, [RequestOptions::SINK => $tmpFile]);
                    } catch (\Exception $e) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    if (!is_readable($tmpFile)) {
                        echo 'x';
                        continue;
                    }
                    // 识别
                    $r = new RecognizeBusinessLicense($tmpFile);
                    try {
                        $rResult = $r->recognize();
                    } catch (\Exception $e) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    if (!isset($rResult['Data']['Name'])) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    $ossArr = FileUtil::uploadFile($tmpFile);
                    if (!isset($ossArr['path']) || !is_string($ossArr['path'])) {
                        @unlink($tmpFile);
                        echo 'x';
                        continue;
                    }
                    $resultModel = RecognizeBusinessLicenseResult::add($ossArr['path'], $rResult['Data']);
                    $model->url = $ossArr['path'];
                    $model->isPublic = 1;
                    $model->save();
                    echo '√';
                }
            });
        return 0;
    }
}
